package com.example.flutter_native_map
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.location.LocationManager.GPS_PROVIDER
import android.util.Log
import androidx.core.app.ActivityCompat
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.Circle
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.util.UUID


class FlutterNativeMapPlugin: FlutterPlugin,ActivityAware, EventChannel.StreamHandler,
  MethodCallHandler{
  private lateinit var locationListener: AMapLocationListener
  private lateinit var location: AMapLocationClient
  private var aMap: AMap? = null
  private lateinit var activity: Activity
  private val TAG: String="emmmmmmm"
  private var channel: MethodChannel? = null
  private var event: EventChannel? = null
  private var eventSink: EventSink? = null
  private var circleMap=HashMap<String,Circle>()
  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_native_map")
    event = EventChannel(flutterPluginBinding.binaryMessenger, "flutter_native_map_event")
    channel?.setMethodCallHandler(this)
    event?.setStreamHandler(this)
    flutterPluginBinding.platformViewRegistry.registerViewFactory("mapNativeView", NativeMapViewFactory{
      aMap=it
      eventSink?.success("加载完成")
    })
  }
  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel!!.setMethodCallHandler(null)
    event!!.setStreamHandler(null)
    circleMap.clear()
  }
  override fun onListen(arguments: Any?, events: EventSink) {
    eventSink = events
  }

  override fun onCancel(arguments: Any?) {
    eventSink = null
  }

  @SuppressLint("ServiceCast")
  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    when (call.method) {
      "requestPermission" -> {
        ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), 1)
        result.success("")
      }
      "checkPermission"->{
        if (ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED||ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
          result.success(false)
        }else{
          result.success(true)
        }
      }
      "moveCameraTo"->{
        if(aMap==null){
          result.success(false)
        }else{
          try {
            aMap?.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(call.argument<Double>("latitude")!!,call.argument<Double>("longitude")!!),15f,0.0f,0.0f)))
            result.success(true)
          }catch (e:Exception){
            e.printStackTrace()
            result.success(false)
          }
        }
      }

      "drawCircle"->{
        if(aMap==null){
          result.success("aMap未初始化")
        }else{
          try {
            val latLng = LatLng(call.argument<Double>("latitude")!!,call.argument<Double>("longitude")!!)
            val circle = aMap!!.addCircle(
              CircleOptions()
                .center(latLng)
                .radius(call.argument<Double>("radius")!!)
                .fillColor(call.argument<Int>("fillColor")!!)
                .strokeColor(call.argument<Int>("strokeColor")!!)
                .strokeWidth(call.argument<Float>("strokeWidth")!!)
            )
            val uuid=UUID.randomUUID().toString()
            circleMap[uuid]=circle
            result.success(uuid)
          }catch (e:Exception){
            e.printStackTrace()
            result.success("绘制出错")
          }
        }
      }
      "removeCircle"->{
        if(aMap==null){
          result.success("aMap未初始化")
        }else{
          try {
            val circleId = call.argument<String>("circle")!!
            val circle = circleMap[circleId]
            if (circle != null) {
              circle.remove()
              circleMap.remove(circleId)
              result.success("删除成功")
            } else {
              result.success("找不到对应的 Circle")
            }
          }catch (e:Exception){
            e.printStackTrace()
            result.success("绘制出错")
          }
        }
      }
      "getLocation"->{
        if(aMap==null){
          result.success("aMap未初始化")
        }else{
          getLocation(result)
        }
      }
      "isGpsOpen"->{
       try{
         val locationService = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
         result.success(locationService.isProviderEnabled(GPS_PROVIDER))
       }
       catch (e:Exception){
         e.printStackTrace()
         result.success(false)
       }
      }
      else -> result.notImplemented()
    }
  }

  private fun getLocation(result: MethodChannel.Result) {
    locationListener=AMapLocationListener{
      result.success("${it.toJson(1)}")
      removeListener()
    }
    location.setLocationListener(locationListener)
    location.startLocation()
  }

  private fun removeListener() {
    location.stopLocation()
    location.unRegisterLocationListener(locationListener)
  }


  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    Log.i(TAG, "onAttachedToActivity: ")
    activity=binding.activity
    AMapLocationClient.updatePrivacyAgree(activity,true)
    AMapLocationClient.updatePrivacyShow(activity,true,true)
    location=AMapLocationClient(activity)
    val options= AMapLocationClientOption()
    options.isBeidouFirst=true
    options.isWifiScan=true
    options.isNeedAddress=true
    options.isOnceLocation=true
    options.locationMode= AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
    location.setLocationOption(options)
  }

  override fun onDetachedFromActivityForConfigChanges() {
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
  }

  override fun onDetachedFromActivity() {
    Log.i(TAG, "onDetachedFromActivity: ")
  }
}